cmake_minimum_required(VERSION 3.10)

option(BUILD_64BIT "build 64 BIT version." OFF )
option(BUILD_WITH_AS "build with AS." ON )
option(BUILD_DEBUG "build with debug symbol." ON )

project(c-template)
set(main_name c-template)

# Add the cmake folder so the FindSphinx module is found
set(CMAKE_MODULE_PATH "${PROJECT_SOURCE_DIR}/cmake" ${CMAKE_MODULE_PATH})
include(Utility)

set(TARGET_PLATFORM "LINUX")
string(TIMESTAMP BUILD_SYS_DATE_INFO "%Y.%m.%d")
add_definitions(-DTARGET_PLATFORM_${TARGET_PLATFORM} -DBUILD_DATE="${BUILD_SYS_DATE_INFO}")

string(TOUPPER ${TARGET_PLATFORM} TARGET_PLATFORM)
string(TOLOWER ${TARGET_PLATFORM} TARGET_PLATFORM_LC)


set(AS_FLAGS)

if (NOT BUILD_64BIT)
    MESSAGE("Build 32bits version.")
    set(AS_FLAGS "${AS_FLAGS} -m32")
endif()

# enable debug symbol
if (BUILD_DEBUG)
set(AS_FLAGS "${AS_FLAGS} -g")
endif()

if (BUILD_WITH_AS)
set(AS_FLAGS "${AS_FLAGS} -fsanitize=address ")
set(AS_FLAGS "${AS_FLAGS} -fno-omit-frame-pointer -fsanitize-recover=address -fsanitize=leak")
set(AS_FLAGS "${AS_FLAGS} -fsanitize-recover -static-libasan")
endif()

set(CMAKE_C_FLAGS ${CMAKE_C_FLAGS} ${AS_FLAGS})
set(CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS} ${AS_FLAGS})

if (NOT DEFINED THIRD_COMPONENTS)
    if (TARGET_PLATFORM STREQUAL "LINUX")
        set(THIRD_COMPONENTS "cjson" "ulog")
    endif()
endif()

# component list.
set(components core comp1)
if(THIRD_COMPONENTS)
    set(components ${components} 3rd)
endif()

foreach (subfolder IN ITEMS ${components})
    include(${CMAKE_CURRENT_LIST_DIR}/src/${subfolder}/CMakeLists.txt)
    if( EXISTS ${CMAKE_CURRENT_LIST_DIR}/src/${subfolder}/api )
        include_directories("${CMAKE_CURRENT_LIST_DIR}/src/${subfolder}/api")
    endif()
endforeach()

add_executable(${main_name})
target_sources(${main_name} PRIVATE "src/main.c" )
target_link_libraries(${main_name} ${components})
target_link_libraries(${main_name} -Wl,-Map=${main_name}.map)

# UTs and doc will be built for LINUX only.
foreach (subfolder IN ITEMS ${components})
    if(EXISTS ${CMAKE_CURRENT_LIST_DIR}/src/${subfolder}/ut/CMakeLists.txt)
        add_subdirectory(${CMAKE_CURRENT_LIST_DIR}/src/${subfolder}/ut)
    endif()
endforeach()

# doc.
if(EXISTS ${CMAKE_CURRENT_LIST_DIR}/doc/CMakeLists.txt)
    add_subdirectory ("doc")
endif()
